import Cookies from 'js-cookie'
import { getUserTodo } from '@/api/flow/index'
const state = {
  sidebar: {
    opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
    withoutAnimation: false
  },
  device: 'desktop',
  topmenu: sessionStorage.getItem('topmenu'),
  subroutes: '', // sessionStorage.getItem('subroutes')
  todo: 0
}

const mutations = {
  TOGGLE_SIDEBAR: state => {
    state.sidebar.opened = !state.sidebar.opened
    state.sidebar.withoutAnimation = false
    if (state.sidebar.opened) {
      Cookies.set('sidebarStatus', 1)
    } else {
      Cookies.set('sidebarStatus', 0)
    }
  },
  CLOSE_SIDEBAR: (state, withoutAnimation) => {
    Cookies.set('sidebarStatus', 0)
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  TOGGLE_DEVICE: (state, device) => {
    state.device = device
  },
  SET_TOPMENU: (state, topmenu) => {
    state.topmenu = topmenu
    sessionStorage.setItem('topmenu', topmenu)
  },
  SET_SUBROUTES: (state, subroutes) => {
    state.subroutes = subroutes
    // sessionStorage.setItem('subroutes', JSON.stringify(subroutes))
  },
  SET_TODO: (state, todo) => {
    state.todo = todo
    // sessionStorage.setItem('subroutes', JSON.stringify(subroutes))
  }
}

const actions = {
  toggleSideBar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  closeSideBar({ commit }, { withoutAnimation }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  toggleDevice({ commit }, device) {
    commit('TOGGLE_DEVICE', device)
  },
  setTopMenu({ commit }, topmenu) {
    commit('SET_TOPMENU', topmenu)
  },
  setSubroutes({ commit }, subroutes) {
    commit('SET_SUBROUTES', subroutes)
  },
  setTodo({ commit }) {
    return new Promise((resolve, reject) => {
      getUserTodo().then(response => {
        // resetRouter()
        commit('SET_TODO', response.Data)
        resolve(response.Data)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
